//
//  CollView.swift
//  weibo1
//
//  Created by 李进 on 15/10/22.
//  Copyright © 2015年 李进. All rights reserved.
//

import UIKit
import SDWebImage

let collLineSpace: CGFloat = 8.00

let collViewCellID = "collViewCellID"

class CollView: UICollectionView {
    
    
    //声明一个属性来实现数据的接收
    var viewModel: userFriendViewModel? {
        
        didSet{
            //大小等于自动大小
            sizeToFit()
            
            //防止重用
            reloadData()
        
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    init(){
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumLineSpacing = collLineSpace
        layout.minimumInteritemSpacing = collLineSpace
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        //设置数据源方法
        dataSource = self
        
        //设置代理
        delegate = self
        
        //注册cell
        registerClass(CollViewCell.self, forCellWithReuseIdentifier: collViewCellID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// MARK: - 实现collectionview的数据源方法
extension CollView: UICollectionViewDataSource {
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collViewCellID, forIndexPath: indexPath) as! CollViewCell
        
        
        cell.imageURL = viewModel?.thumbnailUrls![indexPath.item]
        
        
        return cell
    }
}

// MARK: - UICollectionViewDelegate
extension CollView: UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //print("点击了我")
        
        var dictinfo:[String:AnyObject] = [CVStatusIndexPathKey:indexPath]
        dictinfo[CVStatusURLsKey] = viewModel?.thumbnailUrls
        
        //发送通知传递参数
        NSNotificationCenter.defaultCenter().postNotificationName(sendNofotier, object: self, userInfo: dictinfo)
        
    }
}

// MARK: - 设置collview的狂堵和高度的方法
extension CollView {
    
    private func calcViewSize() -> CGSize {
        
        // 1. 准备
        // 每行的照片数量
        let rowCount: CGFloat = 3
        // 最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * HomeCellMargin
        let itemWidth = (maxWidth - 2 * collLineSpace) / rowCount
        
        // 2. 设置 layout 的 itemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 3. 获取图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        
        // 计算开始
        // 1> 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 2> 一张图片
        if count == 1 {
            // TODO: - 临时指定大小，稍后再讲
            var size = CGSize(width: 150, height: 120)
            
            let key = viewModel?.thumbnailUrls?.first?.absoluteString
            //使用sdw 获取磁盘上的图片
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
                size = image.size
            }
            
            //图片过窄处理
           size.width = size.width < 40 ? 60 : size.width
            //过宽
            if size.height > 300 {
                let w = CGFloat(300)
                let h = size.height * w / size.width
                
                size = CGSize(width: w, height: h)
            }
            
            // 内部图片的大小
            layout.itemSize = size
            
            // 配图视图的大小
            return size
        }
        
        // 3> 四张图片 2 * 2 的大小
        if count == 4 {
            let w = 2 * itemWidth + collLineSpace
            
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他图片 按照九宫格来显示
        // 计算出行数
        /**
        2 3
        5 6
        7 8 9
        */
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * collLineSpace
        let w = rowCount * itemWidth + (rowCount - 1) * collLineSpace
        
        return CGSize(width: w, height: h)
    }
}


//    func setCollvcWH() -> CGSize{
//        
//        //计算一个item的宽度
//        let rowCount: CGFloat = 3
//        //计算最大宽度
//        let maxW = UIScreen.mainScreen().bounds.width - 2 * collLineSpace
//        //计算单个item的宽度
//        let itemW = (maxW - 2 * collLineSpace) / rowCount
//        
//        
//        //应为改变大小是改变layout的大小,获取cell的layout
//        let layout = collectionViewLayout as! UICollectionViewFlowLayout
//        layout.itemSize = CGSize(width: itemW, height: itemW)
//        
//        //获取图片的数量
//        let count = viewModel?.thumbnailUrls?.count ?? 0
//        
//        //如果没有图片就返回0
//        if count == 0 {
//            
//            return CGSizeZero
//        }
//        
//        if count == 1 {
//            
//            let size = CGSize(width: 150, height: 120)
//            
//            layout.itemSize = size
//            
//            return size
//        }
//        
//        if count == 4 {
//            let w = 2 * itemW + collLineSpace
//            
//            return CGSize(width: w, height: w)
//        }
//        
//        let row = CGFloat((count - 1) / Int(rowCount) + 1)
//        let h = row * itemW + (row - 1) * collLineSpace
//        let w = rowCount * itemW + (rowCount - 1) * collLineSpace
//        return CGSize(width: w, height: h)
//    }
    


/// 自定义cell的布局设置
class CollViewCell:UICollectionViewCell{
    
    var imageURL:NSURL?{
        didSet{
            iconImage.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached])
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setCollCellUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setCollCellUI(){
        
        contentView.addSubview(iconImage)
        
        //设置自动布局
        iconImage.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    //懒加载控件
    private lazy var iconImage: UIImageView = {
        let iv = UIImageView()
        
        // 设置填充模式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        // 需要裁切图片
        iv.clipsToBounds = true
        
        return iv
        
    }()
}


